<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no"/>
  <title>Test Map</title>
  <style>
    html,
    body,
    #viewDiv {
      margin: 0;
      padding: 0;
      width: 100%;
      height: 100%;
    }
  </style>
  <link href="https://openlayers.org/en/v6.3.1/css/ol.css" rel="stylesheet" type="text/css"/>
  <script src="https://openlayers.org/en/v6.3.1/build/ol.js"></script>

</head>
<body class="claro">
<div id="viewDiv"></div>
<script type="text/javascript">
var projection = ol.proj.get("EPSG:3857");
console.log(projection)
var resolutions = [];
for (var i = 0; i < 19; i++) {
  resolutions[i] = Math.pow(2, 18 - i);
}
var tilegrid = new ol.tilegrid.TileGrid({
  origin: [0, 0],
  resolutions: resolutions
});

var baidu_source = new ol.source.TileImage({
  projection: projection,
  tileGrid: tilegrid,
  wrapX: true, // 允许左右无限移动
  tileUrlFunction: function (tileCoord, pixelRatio, proj) {
    if (!tileCoord) {
      return "";
    }
    var z = tileCoord[0];
    var x = tileCoord[1];
    let y = -tileCoord[2] - 1;

    // 百度瓦片服务url将负数使用M前缀来标识
    if (x < 0) {
      x = 'M' + (-x);
    }
    if (y < 0) {
      y = 'M' + (-y);
    }
    return "http://online3.map.bdimg.com/onlinelabel/?qt=tile&x=" + x + "&y=" + y + "&z=" + z + "&styles=pl&udt=20151021&scaler=1&p=1";
  }
});
var baidusource = new ol.source.XYZ({
  projection: 'baidu',
  maxZoom: 18,
  wrapX: true, // 允许左右无限移动
  tileUrlFunction: function (tileCoord, ss, e) {
    var x = tileCoord[1];
    var y = tileCoord[2];
    var z = tileCoord[0];
    console.log(x, y, z, ss, e)
    y = -y
    return "http://online3.map.bdimg.com/tile/?qt=vtile&x=" + x + "&y=" + y + "&z=" + z + "&styles=pl&udt=udt=20170908&scaler=1&p=1"
  },
  tileGrid: new ol.tilegrid.TileGrid({
    resolutions: resolutions,
    origin: [0, 0],
    //extent: ol.extent.applyTransform(extent, projzh.ll2bmerc),
    tileSize: [256, 256]
  })
})

var baidu_layer = new ol.layer.Tile({
  source: baidu_source
});

var map = new ol.Map({
  target: 'viewDiv',
  layers: [baidu_layer],
  view: new ol.View({
    center: [12959773, 4853101],
    zoom: 5,
  })
});
</script>
</body>
</html>
